import Vue from 'vue'
import Vuex from 'vuex'
import {
	getUserInfo
} from "../api/platform/user.js"

import {
	getNeareastCity
} from "@/api/platform/user.js"
import {
	getLocation
} from '@/common/maUtil.js'
Vue.use(Vuex)

const db = uniCloud.database()
const dbCmd = db.command
const store = new Vuex.Store({
	state: {
		hasLogin: !!uni.getStorageSync('uni_id_token'),
		userInfo: uni.getStorageSync('userInfo') || {
			account: {}
		},
		token: uni.getStorageSync('uni_id_token') || '',
		tokenExpired: uni.getStorageSync('uni_id_token_expired') || 0,
		currShop: {},
		hasNavToLogin: false, //为了解决多次跳转到登陆页面的问题
		wxLoginCode: '', // 微信登录所用的code

		currGoods: {
			skus: []
		}, //当前下单的商品
		currSku: null, //当前下单的sku
		shareManId: null, //分享者id

		shareManInfo: uni.getStorageSync('shareManInfo') || null, //分销平台分享者信息

		currentRegion: uni.getStorageSync('currentRegion') || null, 
		userLocation: uni.getStorageSync('userLocation') || null, 

		loginPopup: false, 
	},
	getters: {
		isTokenValid(state) {
			return !!state.token && state.tokenExpired > Date.now()
		}
	},
	mutations: {
		setLoginPopup(state, show) {
			state.loginPopup = show
		},
		setWxLoginCode(state, wxLoginCode) {
			state.wxLoginCode = wxLoginCode
		},
		setCurrentRegion(state, {
			currentRegion = null,
			userLocation = null
		}) {
			if (currentRegion) {
				state.currentRegion = currentRegion
				uni.setStorageSync("currentRegion", currentRegion)
			}
			if (userLocation) {
				state.userLocation = userLocation
				uni.setStorageSync("userLocation", userLocation)
			}
		},
		updateToken(state, {
			token,
			tokenExpired
		}) {
			state.token = token;
			state.tokenExpired = tokenExpired
			uni.setStorageSync('uni_id_token', token)
			uni.setStorageSync('uni_id_token_expired', tokenExpired)
		},
		login(state, userInfo) {
			state.userInfo = userInfo;
			state.hasLogin = true;
			uni.setStorageSync('userInfo', userInfo)
			if (userInfo.shareManInfo) {
				state.shareManInfo = userInfo.shareManInfo
				uni.setStorageSync('shareManInfo', userInfo.shareManInfo)
			}
		},
		logout(state) {
			state.hasLogin = false;
			state.userInfo = {
				account: {}
			};
			state.token = "";
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('uni_id_token')
			uni.removeStorageSync('uni_id_token_expired')
		},
		updateUserInfo(state, userInfo) {
			state.userInfo = userInfo
			uni.setStorageSync('userInfo', userInfo)
			if (userInfo.shareManInfo) {
				state.shareManInfo = userInfo.shareManInfo
				console.log('5')
				uni.setStorageSync('shareManInfo', userInfo.shareManInfo)
			}
		},
		setShareManInfo(state, shareManInfo) {
			state.shareManInfo = shareManInfo
			if (shareManInfo) {
				uni.setStorageSync('shareManInfo', shareManInfo)
			} else {
				uni.removeStorageSync('shareManInfo')
			}
		},
		switchShop(state, shop) {
			state.currShop = shop;
		},
		navToLogin(state, timeout) {
			if (state.hasNavToLogin) {
				return;
			}
			state.hasNavToLogin = true;

			setTimeout(function() {
				uni.navigateTo({
					url: '/pagesFoo/public/login',
				});
			}, timeout || 3000)
		},
		finishLogin(state) {
			state.hasNavToLogin = false;
		},

		setCurrGoods(state, goods) {
			state.currGoods = goods;
		},

		setCurrSku(state, sku) {
			state.currSku = sku;
		},
		setShareManId(state, shareManId) {
			state.shareManId = shareManId
			if (shareManId) {
				uni.setStorageSync('goodsShareManId', shareManId);
			} else {
				uni.removeStorageSync('goodsShareManId');
			}
		},
		setCurrLocation(state, location) {
			state.userLocation = location
		}
	},
	actions: {
		async setShareManId({
			commit,
			state,
			dispatch
		}, shareManId) {
			if (shareManId) {
				try {
					// await dispatch('syncUserInfo')
					let userInfo = state.userInfo
					// if (userInfo.id == shareManId) return // 方便测试注释

					let share = {
						shareManId: shareManId == -1 ? (userInfo.share?.shareManId || null) :
							shareManId, // shareManId == -1 表更新数据库并重新存储shareManId
						shareTime: Date.now()
					}
					switch (userInfo.shareGrade) {
						case 0: // 普通用户
							if (userInfo.share?.shareManId) {
								if ((userInfo.share.shareTime + 259200000) < Date
									.now()) { // 超过3天有效期，清除分享人id
									share.shareManId = null
									share.shareTime = null
								} else {
									delete share.shareTime
								}
							}
							await db.collection('uni-id-users')
								.doc(userInfo._id)
								.update({
									share
								})
							break;
						default: // 达人
							if (userInfo.share?.shareManId) {
								await db.collection('uni-id-users')
									.doc(userInfo._id)
									.update({
										share: {
											shareManId: null,
											shareTime: null
										}
									})
							}
							break;
					}
					userInfo.share = share
					commit('updateUserInfo', userInfo) // 仅为跟数据库数据同步
					commit('setShareManId', share.shareManId)
				} catch (e) {
					console.error("saveShareManId: ", e);
				}
			} else { // 仅本地清空
				commit('setShareManId', null)
			}
		},
		async getCurrRegion({
			commit,
			state
		}) {
			
			// if (state.userLocation && state.currentRegion) {
			// 	return {
			// 		userLocation: state.userLocation,
			// 		currRegion: state.currentRegion
			// 	}
			// }
			return new Promise((resolve, reject) => {
				getLocation().then(async loc => {
					if (!state.currentRegion) {
						try{
							let currentRegion = await getNeareastCity({
								userLocation: loc
							})
							commit('setCurrentRegion', {
								currentRegion,
								userLocation: loc
							})
							resolve({
								userLocation: loc,
								currRegion: state.currentRegion
							})
						}catch(e){
							console.error(e)
							reject(e)
						}
					} else {
						resolve({
							userLocation: loc,
							currRegion: state.currentRegion
						})
					}
				}).catch(err => {
					console.error(err)
					reject(err)
				})
				// let getLocation = function () {
				// 	uni.getLocation({
				// 		type: 'gcj02',
				// 		success: async (loc) => {
				// 			let t = {
				// 				longitude: loc.longitude,
				// 				latitude: loc.latitude
				// 			}
				// 			try{
				// 				let currentRegion = await getNeareastCity({
				// 					userLocation: t
				// 				})
				// 				commit('setCurrentRegion', {
				// 					currentRegion,
				// 					userLocation: t
				// 				})
				// 				resolve({
				// 					userLocation: state.userLocation,
				// 					currRegion: state.currentRegion
				// 				})
				// 			}catch(e){
				// 				console.error(e)
				// 				reject(e)
				// 			}
				// 		},
				// 		fail: async (err) => {
				// 			console.error(err)
				// 			try{
				// 				let currentRegion = await getNeareastCity({})
				// 				commit('setCurrentRegion', {
				// 					currentRegion
				// 				})
				// 				resolve({
				// 					userLocation: state.userLocation,
				// 					currRegion: state.currentRegion
				// 				})
				// 			}catch(e){
				// 				console.error(err)
				// 				reject(err)
				// 			}
				// 		}
				// 	})
				// }
				// // #ifdef MP-WEIXIN
				// uni.getSetting({
				// 	success: res => {
				// 		// console.log("scope.userLocation: ", res.authSetting['scope.userLocation']);
				// 		if (!res.authSetting['scope.userLocation']) {
				// 			uni.authorize({
				// 				scope: 'scope.userLocation',
				// 				success: res => {
				// 					uni.startLocationUpdate({
				// 						type: 'gcj02',
				// 						success: () => {
				// 							uni.onLocationChange(loc => {
				// 								console.log('onLocationChange', loc)
				// 								commit('setCurrLocation', {
				// 									longitude: loc.longitude,
				// 									latitude: loc.latitude
				// 								})
				// 							})
				// 						},
				// 						fail: (err) => {
				// 							console.error(err)
				// 						}
				// 					})
				// 					getLocation()
				// 				},
				// 				fail: async err => {
				// 					console.log('拒绝位置授权');

				// 					uni.showModal({
				// 						title: "请先打开位置权限",
				// 						cancelText: "取消",
				// 						confirmText: "去打开",
				// 						success: async (res) => {
				// 							if (res.confirm) {
				// 								uni.openSetting({
				// 									success: (
				// 										res
				// 										) => {
				// 										getLocation()
				// 									},
				// 								});
				// 							} else {
				// 								resolve(null)
				// 							}
				// 						}
				// 					})
				// 				}
				// 			})
				// 		} else {
				// 			getLocation()
				// 		}
				// 	}
				// })
				// // #endif
				// // #ifndef MP-WEIXIN
				// getLocation()
				// // #endif
			})
		},
		async verifyLocation({
			commit
		}) {
			let currentRegion = null
			let userLocation = null
			// 没开启手机gps定位时获取默认位置
			let notGpsLocation = async function() {
				currentRegion = await getNeareastCity({
					userLocation
				})
				userLocation = {
					longitude: currentRegion.location.coordinates[0],
					latitude: currentRegion.location.coordinates[1]
				}
				commit('setCurrentRegion', {
					currentRegion,
					userLocation
				})
			}

			// 获取位置
			let getLocation = function() {
				uni.getLocation({
					type: "gcj02",
					success: async loc => {
						userLocation = {
							longitude: loc.longitude,
							latitude: loc.latitude
						}
						// console.log("userLocation: ",userLocation);
						let localRegion = uni.getStorageSync("currentRegion")
						if (!localRegion) {
							currentRegion = await getNeareastCity({
								userLocation
							})
						} else {
							currentRegion = localRegion
						}
						commit('setCurrentRegion', {
							currentRegion,
							userLocation
						})
					},
					fail: (err) => {
						console.log("uni.getLocation失败: ", err);
						notGpsLocation()
						// if (err.errCode === 2 && err.errMsg.includes('WIFI_LOCATIONSWITCHOFF')) {
						//   // uni.showModal({
						//   //   title: '提示',
						//   //   content: '请打开手机GPS定位',
						//   //   showCancel: false,
						//   //   success: function (res) {
						//   //     // console.log("res: ",res);
						//   //   }
						//   // });
						// }
					}
				})
			}

			// #ifdef MP-WEIXIN
			uni.getSetting({
				success: res => {
					// console.log("scope.userLocation: ", res.authSetting['scope.userLocation']);
					if (!res.authSetting['scope.userLocation']) {
						uni.authorize({
							scope: 'scope.userLocation',
							success: res => {
								getLocation()
							},
							fail: async err => {
								console.log('拒绝位置授权');

								uni.showModal({
									title: "请先打开位置权限",
									cancelText: "取消",
									confirmText: "去打开",
									success: async (res) => {
										if (res.confirm) {
											uni.openSetting({
												success: (
													res
													) => {
													getLocation
														()
												},
											});
										} else {
											notGpsLocation()
										}
									}
								})
							}
						})
					} else {
						getLocation()
					}
				}
			})
			// #endif

			// #ifndef MP-WEIXIN
			getLocation()
			// #endif
		},
		async syncUserInfo({
			commit,
			showLoading = true
		}) {
			try {
				let currentRegion = uni.getStorageSync('currentRegion')
				let currentCityCode = currentRegion.city.value
				let userInfo = await getUserInfo({
					showLoading
				}, currentCityCode)
				console.log('userInfo: ', userInfo);
				commit('updateUserInfo', userInfo)
			} catch (e) {
				console.error(e)
				throw e
			}
		},
		async getCity({
			commit,
			showLoading = true
		}) {
			if (showLoading) {
				uni.showLoading({
					mask: true
				})
			}
			let [err, loc] = await uni.getLocation({
				type: "gcj02"
			})
			if (!err) {
				let mapWX = require('../js_sdk/map_sdk/qqmap-wx-jssdk.min.js')
				let mapSdk = new mapWX({
					key: 'G2TBZ-DDIWX-3QT4Z-75MUV-XTMV6-5EFGQ'
				})
				try {
					let userRegion = await new Promise((resolve, reject) => {
						mapSdk.reverseGeocoder({
							location: {
								longitude: loc.longitude,
								latitude: loc.latitude
							},
							success: res => {
								console.log(JSON.parse(JSON.stringify(res)));
								resolve(res.result.ad_info.city)
							},
							fail: err => {
								console.log('获取定位城市失败：' + JSON.parse(JSON.stringify(
									err)));
								reject(err)
							}
						})
					})
					var res = await db.collection("t3ds-region").where({
							'city.label': new RegExp(userRegion)
						})
						.field({
							name: true
						})
						.orderBy('createTime', 'desc')
						.limit(1)
						.get()
					if (res.code) {
						if (showLoading) {
							uni.hideLoading()
						}
						throw new Error(res.message)
					}
					if (!res.result.data.length) {
						res = await db.collection("t3ds-region").where({
								'_id': dbCmd.exists(true)
							})
							.field({
								name: true
							})
							.orderBy('createTime', 'desc')
							.limit(1)
							.get()
					}
					if (res.result.data.length) {
						let result = res.result.data[0]
						let region = result.name
						commit('setCurrentRegion', {
							currentRegion: region
						})
						return region
					}
					return {}
				} catch (e) {
					if (showLoading) {
						uni.hideLoading()
					}
					throw e
				}
			}
			if (showLoading) {
				uni.hideLoading()
			}
			return {}
		}
	}
})

export default store